<?php
namespace app\service;
use app\model\UserModel;
use Exception;
use think\facade\Db;
class UserService{
    public function login($userName,$password){
        $data = UserModel::where(['user_name'=>$userName,'password'=>md5($password)])->field('id,user_name,cn_name')->find();
        return $data;
    }
    public function userInfo($userId){
        $user = Db::name('user')->field('id,user_name,cn_name,role_id')->where('id',$userId)->find();
        $right = Db::name('role')->where('id',$user['role_id'])->find();         
        $user['purviews'] = explode(",",$right['purviews']);     
        return $user;
    }

    public function info($userId){
        $user = Db::name('user')->field('id,user_name,cn_name,role_id')->where('id',$userId)->find();          
        return $user;
    }

    public function all($params){
        $where=[];      
        if(!empty($params['keyword'])){
            $where[] = ['company_name','like',"%{$params['keyword']}%"];   
        }
        $users = UserModel::where($where)->select();        
        return $users;
    } 

    public function list($params){
        $where=[];
        $page = $params['page'];
        $pageCount = $params['page_count'];
        if(!empty($params['keyword'])){
            $where[] = ['cn_name|user_name','like',"%{$params['keyword']}%"];   
        }
        $data = UserModel::alias('a')->field('a.*,b.role_name')->join('role b','a.role_id=b.id')->where($where)->page($page,$pageCount)->order('id','desc')->select();         
        $count = UserModel::alias('a')->where($where)->count();       
        return ["list"=>$data,"count"=>$count];
    }

    public function save($params){    
        $data = UserModel::where('user_name',$params['user_name'])->find();          
        if(empty($params['id'])){           
            if($data){
                throw new Exception("用户已存在");
            }
            if(!empty($params['password'])){
                $params['password'] = md5($params['password']);
            }            
            $data = UserModel::create($params); 
        }else{            
            if($data && $data['id']!=$params['id']){
                throw new Exception("用户已存在");
            }
            if(!empty($params['password'])){
                $params['password'] = md5($params['password']);
            }  
            $data = UserModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = UserModel::destroy($params['id']);         
        return $data;
    }
   
}